/**
 * 将 .env 的配置注入到 @idmy/core 中
 */
import { appConfig, httpConfig, HttpRequestConfig, loginConfig, rbacConfig } from '@idmy/core'
import { isNil } from 'lodash-es'
// @ts-ignore
import { version } from '../../package.json'

const getBoolean = (key: any, dv: boolean): boolean => (isNil(import.meta.env['VITE_' + key]) ? dv : import.meta.env['VITE_' + key] === 'true')

/**appConfig**/
appConfig.app.initCfg = true
appConfig.app.key = import.meta.env.VITE_APP_KEY
appConfig.app.title = import.meta.env.VITE_APP_TITLE
appConfig.app.alias = import.meta.env.VITE_APP_ALIAS ?? ''
appConfig.app.version = parseInt(version.replaceAll(/\D/g, ''))
appConfig.env = import.meta.env.MODE === 'develop.local' ? 'dev' : import.meta.env.MODE
appConfig.security.encrypt = getBoolean(import.meta.env.VITE_SECURITY_ENCRYPT, false)
appConfig.security.secret = import.meta.env.VITE_SECURITY_SECRET

/**httpConfig**/
httpConfig.isCache = false
httpConfig.axios.withCredentials = true
/**authConfig**/
rbacConfig.root = getBoolean(import.meta.env.VITE_ROOT, false)
rbacConfig.permission = getBoolean(import.meta.env.VITE_PERMISSION, false)
rbacConfig.role = getBoolean(import.meta.env.VITE_ROLE, false)

appConfig.app.keys = {
  universe: import.meta.env.VITE_APP_URL_universe,
  oauth: import.meta.env.VITE_APP_URL_oauth,
  login: import.meta.env.VITE_APP_URL_login,
  user: import.meta.env.VITE_APP_URL_user,
  sys: import.meta.env.VITE_APP_URL_sys,
  rbac: import.meta.env.VITE_APP_URL_rbac,
}
/**loginConfig**/
loginConfig.loginUrl = import.meta.env.VITE_LOGIN_URL
loginConfig.tokenExpOffset = 0
loginConfig.getServerRefreshToken = (refresh_token: string, config: HttpRequestConfig) => {
  config.appKey = 'oauth'
  return http.postForm('/oauth/token', { grant_type: 'refresh_token', refresh_token, client_id: 'universe' }, config)
}
/**numberConfig**/
appConfig.number.currencyUnitValue = 1
